import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

// 好友信息接口
export interface Friend {
  id: string
  username: string
  nickname: string
  avatar: string
  signature: string
  status: number // 0: 离线, 1: 在线
  lastSeen?: Date
  groupId: string
  isFavorite: boolean
  addedTime: Date
}

// 好友分组接口
export interface FriendGroup {
  id: string
  name: string
  isExpanded: boolean
  friendCount: number
}

// 好友请求接口
export interface FriendRequest {
  id: string
  fromUserId: string
  fromUsername: string
  fromNickname: string
  fromAvatar: string
  message: string
  status: 'pending' | 'accepted' | 'rejected'
  timestamp: Date
}

// 好友状态管理
export const useFriendStore = defineStore('friend', () => {
  const friends = ref<Friend[]>([])
  const friendGroups = ref<FriendGroup[]>([])
  const friendRequests = ref<FriendRequest[]>([])
  const searchKeyword = ref('')

  // 在线好友
  const onlineFriends = computed(() => {
    return friends.value.filter((friend) => friend.status === 1)
  })

  // 离线好友
  const offlineFriends = computed(() => {
    return friends.value.filter((friend) => friend.status === 0)
  })

  // 收藏好友
  const favoriteFriends = computed(() => {
    return friends.value.filter((friend) => friend.isFavorite)
  })

  // 按分组分类的好友
  const friendsByGroup = computed(() => {
    const grouped: Record<string, Friend[]> = {}

    friendGroups.value.forEach((group) => {
      grouped[group.id] = friends.value.filter((friend) => friend.groupId === group.id)
    })

    return grouped
  })

  // 搜索好友
  const filteredFriends = computed(() => {
    if (!searchKeyword.value.trim()) {
      return friends.value
    }

    const keyword = searchKeyword.value.toLowerCase()
    return friends.value.filter(
      (friend) =>
        friend.nickname.toLowerCase().includes(keyword) ||
        friend.username.toLowerCase().includes(keyword) ||
        friend.signature.toLowerCase().includes(keyword),
    )
  })

  // 待处理的好友请求数量
  const pendingRequestsCount = computed(() => {
    return friendRequests.value.filter((req) => req.status === 'pending').length
  })

  // 添加好友
  const addFriend = (friend: Omit<Friend, 'id' | 'addedTime'>) => {
    const newFriend: Friend = {
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      ...friend,
      addedTime: new Date(),
    }

    friends.value.push(newFriend)
    updateGroupFriendCount()
    return newFriend
  }

  // 删除好友
  const removeFriend = (friendId: string) => {
    const index = friends.value.findIndex((friend) => friend.id === friendId)
    if (index >= 0) {
      friends.value.splice(index, 1)
      updateGroupFriendCount()
      return true
    }
    return false
  }

  // 更新好友信息
  const updateFriend = (friendId: string, updates: Partial<Friend>) => {
    const friend = friends.value.find((f) => f.id === friendId)
    if (friend) {
      Object.assign(friend, updates)
      return friend
    }
    return null
  }

  // 切换好友收藏状态
  const toggleFavorite = (friendId: string) => {
    const friend = friends.value.find((f) => f.id === friendId)
    if (friend) {
      friend.isFavorite = !friend.isFavorite
      return friend.isFavorite
    }
    return false
  }

  // 移动好友到其他分组
  const moveFriendToGroup = (friendId: string, groupId: string) => {
    const friend = friends.value.find((f) => f.id === friendId)
    if (friend) {
      friend.groupId = groupId
      updateGroupFriendCount()
      return true
    }
    return false
  }

  // 添加好友分组
  const addFriendGroup = (name: string) => {
    const newGroup: FriendGroup = {
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      name,
      isExpanded: true,
      friendCount: 0,
    }

    friendGroups.value.push(newGroup)
    return newGroup
  }

  // 删除好友分组
  const removeFriendGroup = (groupId: string) => {
    // 不能删除默认分组
    if (groupId === 'default') return false

    // 将该分组的好友移动到默认分组
    friends.value.forEach((friend) => {
      if (friend.groupId === groupId) {
        friend.groupId = 'default'
      }
    })

    const index = friendGroups.value.findIndex((group) => group.id === groupId)
    if (index >= 0) {
      friendGroups.value.splice(index, 1)
      updateGroupFriendCount()
      return true
    }
    return false
  }

  // 重命名好友分组
  const renameFriendGroup = (groupId: string, newName: string) => {
    const group = friendGroups.value.find((g) => g.id === groupId)
    if (group) {
      group.name = newName
      return true
    }
    return false
  }

  // 切换分组展开状态
  const toggleGroupExpanded = (groupId: string) => {
    const group = friendGroups.value.find((g) => g.id === groupId)
    if (group) {
      group.isExpanded = !group.isExpanded
      return group.isExpanded
    }
    return false
  }

  // 发送好友请求
  const sendFriendRequest = (toUserId: string, message: string = '') => {
    const request: FriendRequest = {
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      fromUserId: 'current-user', // 应该从用户store获取
      fromUsername: 'current-user',
      fromNickname: '当前用户',
      fromAvatar: '/default-avatar.png',
      message,
      status: 'pending',
      timestamp: new Date(),
    }

    // 这里应该发送到服务器
    console.log('发送好友请求:', request)
    return request
  }

  // 处理好友请求
  const handleFriendRequest = (requestId: string, action: 'accept' | 'reject') => {
    const request = friendRequests.value.find((req) => req.id === requestId)
    if (!request) return false

    request.status = action === 'accept' ? 'accepted' : 'rejected'

    if (action === 'accept') {
      // 添加为好友
      addFriend({
        username: request.fromUsername,
        nickname: request.fromNickname,
        avatar: request.fromAvatar,
        signature: '',
        status: 1, // 默认在线
        groupId: 'default',
        isFavorite: false,
      })
    }

    return true
  }

  // 更新分组好友数量
  const updateGroupFriendCount = () => {
    friendGroups.value.forEach((group) => {
      group.friendCount = friends.value.filter((friend) => friend.groupId === group.id).length
    })
  }

  // 设置搜索关键词
  const setSearchKeyword = (keyword: string) => {
    searchKeyword.value = keyword
  }

  // 初始化模拟数据
  const initMockData = () => {
    // 初始化分组
    friendGroups.value = [
      { id: 'default', name: '我的好友', isExpanded: true, friendCount: 0 },
      { id: 'family', name: '家人', isExpanded: true, friendCount: 0 },
      { id: 'colleagues', name: '同事', isExpanded: true, friendCount: 0 },
      { id: 'classmates', name: '同学', isExpanded: false, friendCount: 0 },
    ]

    // 初始化好友
    friends.value = [
      {
        id: 'friend-1',
        username: 'zhangsan',
        nickname: '张三',
        avatar: '/avatars/user1.jpg',
        signature: '今天天气真不错',
        status: 1, // 在线
        groupId: 'default',
        isFavorite: true,
        addedTime: new Date(Date.now() - 1000 * 60 * 60 * 24 * 30),
      },
      {
        id: 'friend-2',
        username: 'lisi',
        nickname: '李四',
        avatar: '/avatars/user2.jpg',
        signature: '忙碌的一天',
        status: 1, // 在线
        groupId: 'colleagues',
        isFavorite: false,
        addedTime: new Date(Date.now() - 1000 * 60 * 60 * 24 * 15),
      },
      {
        id: 'friend-3',
        username: 'wangwu',
        nickname: '王五',
        avatar: '/avatars/user3.jpg',
        signature: '学习使我快乐',
        status: 1, // 在线
        groupId: 'classmates',
        isFavorite: false,
        addedTime: new Date(Date.now() - 1000 * 60 * 60 * 24 * 7),
      },
      {
        id: 'friend-4',
        username: 'zhaoliu',
        nickname: '赵六',
        avatar: '/avatars/user4.jpg',
        signature: '生活很美好',
        status: 0, // 离线
        lastSeen: new Date(Date.now() - 1000 * 60 * 60 * 2),
        groupId: 'family',
        isFavorite: true,
        addedTime: new Date(Date.now() - 1000 * 60 * 60 * 24 * 60),
      },
    ]

    // 初始化好友请求
    friendRequests.value = [
      {
        id: 'req-1',
        fromUserId: 'user-new-1',
        fromUsername: 'newuser1',
        fromNickname: '新用户1',
        fromAvatar: '/avatars/new1.jpg',
        message: '你好，我们可以成为好友吗？',
        status: 'pending',
        timestamp: new Date(Date.now() - 1000 * 60 * 30),
      },
    ]

    updateGroupFriendCount()
  }

  return {
    friends,
    friendGroups,
    friendRequests,
    searchKeyword,
    onlineFriends,
    offlineFriends,
    favoriteFriends,
    friendsByGroup,
    filteredFriends,
    pendingRequestsCount,
    addFriend,
    removeFriend,
    updateFriend,
    toggleFavorite,
    moveFriendToGroup,
    addFriendGroup,
    removeFriendGroup,
    renameFriendGroup,
    toggleGroupExpanded,
    sendFriendRequest,
    handleFriendRequest,
    setSearchKeyword,
    initMockData,
  }
})
